package ch.zbw.sysventory.server.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import ch.zbw.sysventory.server.model.Computer;
import ch.zbw.sysventory.server.model.ComputerScan;
import ch.zbw.sysventory.server.model.ComputerScanResult;
import ch.zbw.sysventory.server.repository.ComputerScanRepository;
import ch.zbw.sysventory.server.repository.ComputerScanResultRepository;
import ch.zbw.sysventory.server.service.ComputerScanService;

@Transactional
@Service
public class ComputerScanServiceImpl implements ComputerScanService {

	@Autowired(required = true)
	private ComputerScanRepository computerScanRepository;

	@Autowired(required = true)
	private ComputerScanResultRepository computerScanResultRepository;

	@Override
	public ComputerScan get(Long id) {
		return this.computerScanRepository.findOne(id);
	}

	@Override
	public List<ComputerScan> list() {
		return this.computerScanRepository.findAll(new Sort(Direction.DESC, "startTimeStamp"));
	}

	@Override
	public ComputerScan save(ComputerScan computerScan) {
		return this.computerScanRepository.saveAndFlush(computerScan);
	}

	@Override
	public ComputerScan getLatestScan() {
		List<ComputerScan> list = this.list();
		if (list.size() > 0)
			return list.get(0);
		return null;
	}

	@Override
	public List<ComputerScan> listComputerScansBetween(Date date1, Date date2) {
		return this.computerScanRepository.findByStartTimeStampBetween(date1, date2);
	}

	@Override
	public long countComputerScansBetween(Date date1, Date date2) {
		return this.listComputerScansBetween(date1, date2).size();
	}

	@Override
	public long countComputersScannedBetween(Date date1, Date date2) {
		return this.getComputersScannedBetween(date1, date2).size();
	}

	@Override
	public List<Computer> getComputersScannedBetween(Date date1, Date date2) {
		List<ComputerScan> scans = this.listComputerScansBetween(date1, date2);
		Map<Long, Computer> computers = new HashMap<Long, Computer>();
		Iterator<ComputerScan> scanIterator = scans.iterator();
		while (scanIterator.hasNext()) {
			ComputerScan scan = scanIterator.next();
			List<ComputerScanResult> scanResults = this.computerScanResultRepository.findByComputerScan(scan);
			Iterator<ComputerScanResult> scanResultsIterator = scanResults.iterator();
			while (scanResultsIterator.hasNext()) {
				ComputerScanResult scanResult = scanResultsIterator.next();
				if (scanResult.getComputer() != null)
					computers.put(scanResult.getComputer().getId(), scanResult.getComputer());
			}
		}
		return new ArrayList<Computer>(computers.values());
	}

}
